<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <title>Analyzer 看板</title>
  <style>
    body { font-family: system-ui, Arial; margin: 20px; }
    .filters { display: flex; gap: 12px; margin-bottom: 16px; }
    .panel { border: 1px solid #ddd; padding: 12px; margin-top: 12px; }
    pre { background: #f7f7f7; padding: 8px; overflow: auto; }
  </style>
</head>
<body>
  <h1>数据分析看板</h1>
  <div class="filters">
    <input id="begin" type="date" />
    <input id="end" type="date" />
    <input id="region" placeholder="省份/地区" />
    <input id="city" placeholder="城市" />
    <input id="industry" placeholder="行业" />
    <select id="group_by">
      <option value="">不分组</option>
      <option value="region">按地区</option>
      <option value="city">按城市</option>
      <option value="type">按类型</option>
      <option value="industry">按行业</option>
    </select>
    <label><input id="use_precompute" type="checkbox" />使用预计算</label>
    <button onclick="loadAll()">查询</button>
  </div>

  <div class="panel">
    <h3>项目数量统计</h3>
    <div id="chart_projects" style="width:100%;height:360px"></div>
  </div>
  <div class="panel">
    <h3>金额分桶（预算）</h3>
    <div id="chart_buckets" style="width:100%;height:360px"></div>
  </div>
  <div class="panel">
    <h3>企业中标率</h3>
    <div id="chart_win_rate" style="width:100%;height:360px"></div>
  </div>
  <div class="panel">
    <h3>行业集中度（HHI）</h3>
    <div id="chart_hhi" style="width:100%;height:360px"></div>
  </div>

  <script>
    function q(key) { return document.getElementById(key).value; }
    function checked(id) { return document.getElementById(id).checked; }
    function params(extra) {
      const p = new URLSearchParams();
      const keys = ['begin','end','region','city','industry','group_by'];
      keys.forEach(k => { const v = q(k); if (v) p.append(k, v); });
      if (checked('use_precompute')) p.append('use_precompute', '1');
      if (extra) Object.entries(extra).forEach(([k,v]) => p.append(k,v));
      return p.toString();
    }
    async function fetchJson(url) {
      const res = await fetch(url);
      const json = await res.json();
      return json.data;
    }
    async function loadAll() {
      const base = '/analyzer/api/v1/analyzer';
      const pc = await fetchJson(`${base}/projects/count?${params()}`);
      const ab = await fetchJson(`${base}/amount/buckets?${params({source:'budget'})}`);
      const wr = await fetchJson(`${base}/company/win-rate?${params()}`);
      const hhi = await fetchJson(`${base}/industry/hhi?${params()}`);
      renderProjects(pc);
      renderBuckets(ab);
      renderWinRate(wr);
      renderHHI(hhi);
    }
    function renderProjects(pc){
      const days = [...new Set(pc.map(x=>x.day))].sort();
      const groupBy = q('group_by');
      const nameMap = {'region':'region','city':'city','type':'project_type','industry':'industry'};
      let series = [];
      if (!groupBy){
        const map = new Map();
        pc.forEach(x=>map.set(x.day, x.project_count));
        series = [{name:'项目数',type:'line',data:days.map(d=>map.get(d)||0)}];
      } else {
        const grp = nameMap[groupBy];
        const labels = [...new Set(pc.map(x=>x[grp]||''))];
        series = labels.map(lbl=>{
          const map = new Map();
          pc.filter(x=> (x[grp]||'')===lbl).forEach(x=>map.set(x.day, x.project_count));
          return {name: lbl||'未定义', type:'line', data: days.map(d=>map.get(d)||0)};
        });
      }
      const chart = echarts.init(document.getElementById('chart_projects'));
      chart.setOption({
        tooltip:{trigger:'axis'},
        legend:{},
        xAxis:{type:'category',data:days},
        yAxis:{type:'value'},
        series
      });
    }
    function renderBuckets(ab){
      const categories = ab.map(x=>x.bucket);
      const counts = ab.map(x=>x.count);
      const chart = echarts.init(document.getElementById('chart_buckets'));
      chart.setOption({
        tooltip:{trigger:'axis'},
        xAxis:{type:'category',data:categories},
        yAxis:{type:'value'},
        series:[{name:'数量',type:'bar',data:counts}]
      });
    }
    function renderWinRate(wr){
      const names = wr.map(x=>x.company_name||('ID '+x.company_id));
      const rates = wr.map(x=>Number((x.win_rate*100).toFixed(2)));
      const chart = echarts.init(document.getElementById('chart_win_rate'));
      chart.setOption({
        tooltip:{trigger:'axis'},
        xAxis:{type:'category',data:names},
        yAxis:{type:'value'},
        series:[{name:'中标率(%)',type:'bar',data:rates}]
      });
    }
    function renderHHI(hhi){
      const industries = hhi.map(x=>x.industry||'未定义');
      const values = hhi.map(x=>Number(x.hhi.toFixed(2)));
      const chart = echarts.init(document.getElementById('chart_hhi'));
      chart.setOption({
        tooltip:{trigger:'axis'},
        xAxis:{type:'category',data:industries},
        yAxis:{type:'value'},
        series:[{name:'HHI',type:'bar',data:values}]
      });
    }
  </script>
  <script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
</body>
</html>
